package com.gome.boot.config.web;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.gome.boot.common.util.CommonUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;

/**
 * SpringMvc应用基础配置.
 *
 * @author baoxiufeng
 */
@EnableWebMvc
public abstract class BaseMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        List<String> locations = getResourceLocations();
        if (CommonUtils.isEmpty(locations)) {
            return;
        }
        for (String location : locations) {
            registry.addResourceHandler(location + "**").addResourceLocations("classpath:" + location).setCachePeriod(31556926);
        }
        super.addResourceHandlers(registry);
    }

    private ObjectMapper objectMapper() {
        Jackson2ObjectMapperFactoryBean bean = new Jackson2ObjectMapperFactoryBean();
        bean.setIndentOutput(true);
        bean.setSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bean.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        bean.afterPropertiesSet();
        ObjectMapper objectMapper = bean.getObject();
        // 属性值为null不会被序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // map中value为null不会被序列化
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        // 忽略未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 空对象不抛出异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        return objectMapper;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper());
        converters.add(converter);
    }

    /**
     * 获取静态资源路径列表.
     * <br/>src/main/webapp下：
     * <br/>    /styles/
     * <br/>    /scripts/
     * <br/>    /images/
     * <br/>    /pages/
     * <br/>    ......
     *
     * @return 静态资源路径列表
     */
    protected abstract List<String> getResourceLocations();
}
